<template>
  <div class="comparative-report">
    <el-card>
      <div slot="header">
        <span>对比分析</span>
        <el-button style="float: right;" type="primary" size="mini" @click="handleCompareConfig">
          配置对比
        </el-button>
      </div>

      <!-- 对比结果展示 -->
      <div v-if="Object.keys(compareData).length > 0">
        <!-- 数据概览 -->
        <div class="compare-summary" style="margin-bottom: 20px;">
          <el-row :gutter="20">
            <el-col :span="6" v-if="compareData.comparison_type === 'period'">
              <div class="summary-card">
                <h4>当前期间</h4>
                <p>{{ compareData.current_period.start_date }} 至 {{ compareData.current_period.end_date }}</p>
              </div>
            </el-col>
            <el-col :span="6" v-if="compareData.comparison_type === 'period'">
              <div class="summary-card">
                <h4>对比期间</h4>
                <p>{{ compareData.compare_period.start_date }} 至 {{ compareData.compare_period.end_date }}</p>
              </div>
            </el-col>
            <el-col :span="6" v-if="compareData.changes && compareData.changes.points">
              <div class="summary-card">
                <h4>积分发放变化</h4>
                <p :class="compareData.changes.points.total_awarded.change_rate >= 0 ? 'text-success' : 'text-danger'">
                  {{ compareData.changes.points.total_awarded.change_rate }}%
                </p>
              </div>
            </el-col>
            <el-col :span="6" v-if="compareData.changes && compareData.changes.commission">
              <div class="summary-card">
                <h4>佣金产生变化</h4>
                <p :class="compareData.changes.commission.total_amount.change_rate >= 0 ? 'text-success' : 'text-danger'">
                  {{ compareData.changes.commission.total_amount.change_rate }}%
                </p>
              </div>
            </el-col>
          </el-row>

          <!-- 时间对比详细数据 -->
          <div v-if="compareData.comparison_type === 'period' && compareData.current_period && compareData.compare_period" style="margin-top: 20px;">
            <h4 style="margin-bottom: 16px;">📊 详细数据对比</h4>
            <el-table :data="getPeriodTableData()" border style="width: 100%">
              <el-table-column prop="period" label="时间期间" width="200"></el-table-column>
              <el-table-column label="积分数据" align="center">
                <el-table-column prop="points_awarded" label="积分发放" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #409EFF;">{{ scope.row.points_awarded }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="points_consumed" label="积分消费" align="center">
                  <template slot-scope="scope">
                    <span style="color: #F56C6C;">{{ scope.row.points_consumed }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="active_users" label="活跃用户" align="center">
                  <template slot-scope="scope">
                    <span style="color: #67C23A;">{{ scope.row.active_users }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="佣金数据" align="center">
                <el-table-column prop="commission_amount" label="佣金金额" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #E6A23C;">¥{{ scope.row.commission_amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="total_records" label="记录数" align="center">
                  <template slot-scope="scope">
                    <span style="color: #909399;">{{ scope.row.total_records }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="active_merchants" label="活跃商户" align="center">
                  <template slot-scope="scope">
                    <span style="color: #909399;">{{ scope.row.active_merchants }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 详细数据表格 -->
        <div v-if="compareData.campaigns || compareData.merchants" class="detailed-data" style="margin-bottom: 20px;">
          <h3 style="margin-bottom: 16px;">📊 详细数据对比</h3>

          <!-- 活动对比详细数据 -->
          <div v-if="compareData.campaigns">
            <el-table :data="getCampaignTableData()" border style="width: 100%">
              <el-table-column prop="name" label="活动名称" width="200"></el-table-column>
              <el-table-column label="积分数据" align="center">
                <el-table-column prop="points_awarded" label="积分发放" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #409EFF;">{{ scope.row.points_awarded }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="active_users" label="活跃用户" align="center">
                  <template slot-scope="scope">
                    <span style="color: #67C23A;">{{ scope.row.active_users }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="佣金数据" align="center">
                <el-table-column prop="commission_amount" label="佣金金额" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #E6A23C;">¥{{ scope.row.commission_amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="total_records" label="记录数" align="center">
                  <template slot-scope="scope">
                    <span style="color: #909399;">{{ scope.row.total_records }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>

          <!-- 商户对比详细数据 -->
          <div v-if="compareData.merchants">
            <el-table :data="getMerchantTableData()" border style="width: 100%">
              <el-table-column prop="name" label="商户名称" width="200"></el-table-column>
              <el-table-column label="积分数据" align="center">
                <el-table-column prop="points_awarded" label="积分发放" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #409EFF;">{{ scope.row.points_awarded }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="active_users" label="活跃用户" align="center">
                  <template slot-scope="scope">
                    <span style="color: #67C23A;">{{ scope.row.active_users }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column label="佣金数据" align="center">
                <el-table-column prop="commission_amount" label="佣金金额" align="center">
                  <template slot-scope="scope">
                    <span style="font-weight: bold; color: #E6A23C;">¥{{ scope.row.commission_amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="total_records" label="记录数" align="center">
                  <template slot-scope="scope">
                    <span style="color: #909399;">{{ scope.row.total_records }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 对比图表 -->
        <div id="comparativeChart" style="height: 400px;"></div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state" style="text-align: center; padding: 60px 0;">
        <i class="el-icon-data-analysis" style="font-size: 64px; color: #ddd;"></i>
        <p style="color: #999; margin-top: 16px;">请点击"配置对比"按钮开始对比分析</p>
      </div>
    </el-card>

    <!-- 对比配置对话框 -->
    <el-dialog title="配置对比分析" :visible.sync="compareConfigVisible" width="600px">
      <el-form :model="compareForm" label-width="120px">
        <el-form-item label="对比类型">
          <el-radio-group v-model="compareForm.compare_type">
            <el-radio label="period">时间对比</el-radio>
            <el-radio label="merchant">商户对比</el-radio>
            <el-radio label="campaign">活动对比</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="对比指标">
          <el-checkbox-group v-model="compareForm.metrics">
            <el-checkbox label="points">积分数据</el-checkbox>
            <el-checkbox label="commission">佣金数据</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 时间对比配置 -->
        <div v-if="compareForm.compare_type === 'period'">
          <el-form-item label="当前期间">
            <el-date-picker
              v-model="compareForm.current_start"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              style="width: 45%; margin-right: 10px;">
            </el-date-picker>
            <el-date-picker
              v-model="compareForm.current_end"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 45%;">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="对比期间">
            <el-date-picker
              v-model="compareForm.compare_start"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              style="width: 45%; margin-right: 10px;">
            </el-date-picker>
            <el-date-picker
              v-model="compareForm.compare_end"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 45%;">
            </el-date-picker>
            <p style="font-size: 12px; color: #999; margin-top: 5px;">留空则自动计算上一个周期</p>
          </el-form-item>
        </div>

        <!-- 商户对比配置 -->
        <div v-if="compareForm.compare_type === 'merchant'">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="compareForm.current_start"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              style="width: 45%; margin-right: 10px;">
            </el-date-picker>
            <el-date-picker
              v-model="compareForm.current_end"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 45%;">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="选择商户">
            <el-select
              v-model="compareForm.merchant_ids"
              multiple
              placeholder="请选择商户（留空自动选择最活跃的商户）"
              style="width: 100%;"
              :loading="merchantLoading"
              @focus="loadMerchantList">
              <el-option
                v-for="merchant in merchantList"
                :key="merchant.id"
                :label="merchant.name"
                :value="merchant.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 活动对比配置 -->
        <div v-if="compareForm.compare_type === 'campaign'">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="compareForm.current_start"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              style="width: 45%; margin-right: 10px;">
            </el-date-picker>
            <el-date-picker
              v-model="compareForm.current_end"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 45%;">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="选择活动">
            <el-select
              v-model="compareForm.campaign_ids"
              multiple
              placeholder="请选择活动（留空自动选择最活跃的活动）"
              style="width: 100%;"
              :loading="campaignLoading"
              @focus="loadCampaignList">
              <el-option
                v-for="campaign in campaignList"
                :key="campaign.id"
                :label="campaign.name"
                :value="campaign.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="compareConfigVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleStartCompare" :loading="compareLoading">开始对比</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { nfcReportsAPI } from '@/api/nfc'
import ChartMixin from '../mixins/ChartMixin'

export default {
  name: 'ComparativeReport',
  mixins: [ChartMixin],
  props: {
    filters: { type: Object, required: true }
  },
  data() {
    return {
      loading: false,
      compareData: {},

      // 对比配置对话框
      compareConfigVisible: false,
      compareForm: {
        compare_type: 'period', // period, merchant, campaign
        metrics: ['points', 'commission'],
        current_start: '',
        current_end: '',
        compare_start: '',
        compare_end: '',
        merchant_ids: [],
        campaign_ids: []
      },
      compareLoading: false,

      // 基础数据
      merchantList: [],
      campaignList: [],
      merchantLoading: false,
      campaignLoading: false
    }
  },
  watch: {
    filters: { 
      handler() { 
        // 只有当已有对比数据时才重新加载（避免无限循环）
        if (Object.keys(this.compareData).length > 0) {
          this.loadComparativeData()
        }
      }, 
      deep: true 
    }
  },
  mounted() {
    // 默认加载一个时间对比
    this.loadComparativeData()
  },
  methods: {
    // 加载对比数据（自动模式）
    async loadComparativeData() {
      try {
        this.loading = true
        
        // 如果是初始加载，使用默认的时间对比参数
        let compareParams
        if (this.filters.start_date && this.filters.end_date) {
          // 转换为对比分析的参数格式
          compareParams = {
            compare_type: 'period',
            metrics: ['points', 'commission'],
            current_start: this.filters.start_date,
            current_end: this.filters.end_date
            // 不指定 compare_start 和 compare_end，让后端自动计算
          }
        } else {
          // 直接使用传入的参数
          compareParams = this.filters
        }

        console.log('对比分析请求参数:', compareParams)

        const response = await nfcReportsAPI.getComparativeAnalysis(compareParams)
        console.log('对比分析响应:', response)

        if (response.code === 0) {
          this.compareData = response.data

          this.$nextTick(() => {
            this.renderComparativeChart(response.data)
          })
        } else {
          console.warn('对比分析返回错误:', response.message)
          // 不显示错误消息，只是保持空状态
          this.compareData = {}
        }
      } catch (error) {
        console.error('加载对比数据失败:', error)
        this.compareData = {}
      } finally {
        this.loading = false
      }
    },

    // 配置对比分析
    handleCompareConfig() {
      // 初始化默认日期
      const end = this.formatDate(new Date())
      const start = this.formatDate(new Date(Date.now() - 29 * 24 * 60 * 60 * 1000))
      this.compareForm.current_start = start
      this.compareForm.current_end = end
      this.compareConfigVisible = true
    },

    // 开始对比
    async handleStartCompare() {
      try {
        this.compareLoading = true

        // 构建请求参数
        const params = {
          compare_type: this.compareForm.compare_type,
          metrics: this.compareForm.metrics,
          current_start: this.compareForm.current_start,
          current_end: this.compareForm.current_end
        }

        // 根据对比类型添加额外参数
        if (this.compareForm.compare_type === 'period') {
          if (this.compareForm.compare_start) {
            params.compare_start = this.compareForm.compare_start
          }
          if (this.compareForm.compare_end) {
            params.compare_end = this.compareForm.compare_end
          }
        } else if (this.compareForm.compare_type === 'merchant') {
          if (this.compareForm.merchant_ids.length > 0) {
            params.merchant_ids = this.compareForm.merchant_ids
          }
        } else if (this.compareForm.compare_type === 'campaign') {
          if (this.compareForm.campaign_ids.length > 0) {
            params.campaign_ids = this.compareForm.campaign_ids
          }
        }

        console.log('对比分析请求参数:', params)

        // 调用API
        const response = await nfcReportsAPI.getComparativeAnalysis(params)
        console.log('对比分析响应:', response)

        if (response.code === 0) {
          this.compareData = response.data
          this.compareConfigVisible = false

          // 渲染对比图表
          this.$nextTick(() => {
            this.renderComparativeChart(this.compareData)
          })

          this.$message.success('对比分析成功')
        } else {
          this.$message.error(response.message || '对比分析失败')
        }
      } catch (error) {
        console.error('对比分析错误:', error)
        this.$message.error('对比分析失败')
      } finally {
        this.compareLoading = false
      }
    },

    // 渲染对比分析图表
    renderComparativeChart(data) {
      if (!data.chart_data) {
        console.warn('没有图表数据')
        return
      }

      const chartData = data.chart_data

      this.renderChart('comparativeChart', {
        title: {
          text: this.getComparisonTitle(data.comparison_type),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              const value = param.seriesName.includes('佣金') ? '￥' + param.value : param.value
              result += param.marker + param.seriesName + ': ' + value + '<br/>'
            })
            return result
          }
        },
        legend: {
          data: chartData.series ? chartData.series.map(s => s.name) : [],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.categories || []
        },
        yAxis: {
          type: 'value'
        },
        series: chartData.series || []
      })
    },

    // 获取对比标题
    getComparisonTitle(type) {
      const titles = {
        period: '时间对比分析',
        merchant: '商户对比分析',
        campaign: '活动对比分析'
      }
      return titles[type] || '对比分析'
    },

    // 加载商户列表
    async loadMerchantList() {
      if (this.merchantList.length > 0 || this.merchantLoading) {
        return // 已加载或正在加载
      }

      try {
        this.merchantLoading = true
        const response = await nfcReportsAPI.getMerchantList()

        if (response.code === 0) {
          this.merchantList = response.data || []
        } else {
          console.warn('获取商户列表失败:', response.message)
          this.$message.warning('获取商户列表失败')
        }
      } catch (error) {
        console.error('加载商户列表错误:', error)
        this.$message.error('加载商户列表失败')
      } finally {
        this.merchantLoading = false
      }
    },

    // 加载活动列表
    async loadCampaignList() {
      if (this.campaignList.length > 0 || this.campaignLoading) {
        return // 已加载或正在加载
      }

      try {
        this.campaignLoading = true
        const response = await nfcReportsAPI.getCampaignList()

        if (response.code === 0) {
          this.campaignList = response.data || []
        } else {
          console.warn('获取活动列表失败:', response.message)
          this.$message.warning('获取活动列表失败')
        }
      } catch (error) {
        console.error('加载活动列表错误:', error)
        this.$message.error('加载活动列表失败')
      } finally {
        this.campaignLoading = false
      }
    },

    // 获取活动表格数据
    getCampaignTableData() {
      if (!this.compareData.campaigns) {
        return []
      }

      const tableData = []
      Object.keys(this.compareData.campaigns).forEach(campaignId => {
        const campaign = this.compareData.campaigns[campaignId]
        const pointsData = campaign.data.points || {}
        const commissionData = campaign.data.commission || {}

        tableData.push({
          name: campaign.name,
          points_awarded: pointsData.total_awarded || 0,
          active_users: pointsData.active_users || 0,
          commission_amount: commissionData.total_amount || 0,
          total_records: commissionData.total_records || 0
        })
      })

      return tableData
    },

    // 获取商户表格数据
    getMerchantTableData() {
      if (!this.compareData.merchants) {
        return []
      }

      const tableData = []
      Object.keys(this.compareData.merchants).forEach(merchantId => {
        const merchant = this.compareData.merchants[merchantId]
        const pointsData = merchant.data.points || {}
        const commissionData = merchant.data.commission || {}

        tableData.push({
          name: merchant.name,
          points_awarded: pointsData.total_awarded || 0,
          active_users: pointsData.active_users || 0,
          commission_amount: commissionData.total_amount || 0,
          total_records: commissionData.total_records || 0
        })
      })

      return tableData
    },

    // 获取时间对比表格数据
    getPeriodTableData() {
      if (!this.compareData.current_period || !this.compareData.compare_period) {
        return []
      }

      const currentData = this.compareData.current_period.data || {}
      const compareData = this.compareData.compare_period.data || {}

      const tableData = [
        {
          period: `当前期间 (${this.compareData.current_period.start_date} 至 ${this.compareData.current_period.end_date})`,
          points_awarded: (currentData.points && currentData.points.total_awarded) || 0,
          points_consumed: (currentData.points && currentData.points.total_consumed) || 0,
          active_users: (currentData.points && currentData.points.active_users) || 0,
          commission_amount: (currentData.commission && currentData.commission.total_amount) || 0,
          total_records: (currentData.commission && currentData.commission.total_records) || 0,
          active_merchants: (currentData.commission && currentData.commission.active_merchants) || 0
        },
        {
          period: `对比期间 (${this.compareData.compare_period.start_date} 至 ${this.compareData.compare_period.end_date})`,
          points_awarded: (compareData.points && compareData.points.total_awarded) || 0,
          points_consumed: (compareData.points && compareData.points.total_consumed) || 0,
          active_users: (compareData.points && compareData.points.active_users) || 0,
          commission_amount: (compareData.commission && compareData.commission.total_amount) || 0,
          total_records: (compareData.commission && compareData.commission.total_records) || 0,
          active_merchants: (compareData.commission && compareData.commission.active_merchants) || 0
        }
      ]

      return tableData
    },

    // 简单日期格式化：返回 yyyy-MM-dd
    formatDate(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${d}`
    }
  }
}
</script>

<style scoped>
/* 对比分析样式 */
.compare-summary {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.summary-card {
  background: white;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  text-align: center;
}

.summary-card h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.summary-card p {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

.empty-state {
  color: #999;
}

.empty-state i {
  display: block;
  margin-bottom: 16px;
}

/* 详细数据表格 */
.detailed-data {
  margin-bottom: 20px;
}

.detailed-data h3 {
  margin-bottom: 16px;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

/* 对话框样式 */
.dialog-footer {
  text-align: center;
}

/* 表单样式 */
.el-form-item label {
  font-weight: 500;
  color: #606266;
}

/* 统计卡片样式 */
.stat-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.stat-card .el-card__header {
  background-color: #F5F7FA;
  border-bottom: 1px solid #EBEEF5;
  padding: 18px 20px;
  font-weight: 500;
  color: #303133;
}

.stat-content {
  padding: 20px;
}

.stat-grid {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  padding: 10px;
  background-color: #fafafa;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-value {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;
}

.stat-value .current {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.stat-value .vs {
  font-size: 12px;
  color: #909399;
  padding: 0 5px;
}

.stat-value .compare {
  font-size: 18px;
  font-weight: bold;
  color: #909399;
}

.stat-change {
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-change.positive {
  color: #67C23A;
}

.stat-change.negative {
  color: #F56C6C;
}

.stat-change.zero {
  color: #909399;
}

.change-rate {
  font-size: 12px;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .compare-summary {
    padding: 15px;
  }
  
  .summary-card {
    padding: 12px;
  }
  
  .summary-card h4 {
    font-size: 13px;
  }
  
  .summary-card p {
    font-size: 14px;
  }
  
  .stat-grid {
    gap: 10px;
  }
  
  .stat-item {
    padding: 8px;
  }
  
  .stat-value .current,
  .stat-value .compare {
    font-size: 16px;
  }
  
  .detailed-data h3 {
    font-size: 16px;
  }
}
</style>